package com.chahu.servlet.backend;

import com.chahu.entity.Snack;
import com.chahu.service.UploadService;
import com.chahu.service.impl.UploadServiceImpl;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIR = "uploads";

    UploadService uploadService;

    @Override
    public void init() throws ServletException {
        uploadService = new UploadServiceImpl();
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String create_time = request.getParameter("create_time");
        Integer categoryId = Integer.parseInt(request.getParameter("category_id"));
        Integer inventory = Integer.parseInt(request.getParameter("inventory"));

        Part filePart = request.getPart("image");
        String fileName = UUID.randomUUID().toString() + "_" + filePart.getSubmittedFileName();

        String basePath = getServletContext().getRealPath("/static/image/");

        String filePath = basePath + fileName;
        filePart.write(filePath);

        Snack snack = new Snack();
        snack.setCategoryId(categoryId);
        snack.setCreateTime(LocalDateTime.now());
        snack.setImage("static/image/" + fileName);
        snack.setPrice(new BigDecimal(price));
        snack.setName(name);
        snack.setUpdateTime(LocalDateTime.now());
        snack.setInventory(inventory);
        uploadService.upload(snack);
        
        response.sendRedirect("static/backend/providerList.html");
    }
}
